package com.freemypay.test.并发.终结任务.检查中断;

import java.util.concurrent.TimeUnit;

public class InterruptingIdion {
	public static void main(String[] args) throws Exception {
		if(args.length != 1) {
			System.out.println("usage:java InterruptingIdiom delay-in-ms");
			System.exit(1);
		}
		Thread t = new Thread(new Blocked3());
		t.start();
		TimeUnit.MILLISECONDS.sleep(new Integer(args[0]));
		t.interrupt();
	}
}

/**
 * 资源清理
 * @author yesixian
 * @date 2018年6月19日
 */
class NeedCleanup {
	private final int id;
	
	public NeedCleanup(int ident) {
		id = ident;
		System.out.println("NeedsCleanup " + id);
	}
	
	public void cleanup() {
		System.out.println("Cleaning up " + id);
	}
}

class Blocked3 implements Runnable {
	private volatile double d = 0.0;

	@Override
	public void run() {
		try {
			while(!Thread.interrupted()) {
				// point1
				NeedCleanup n1 = new NeedCleanup(1);
				try {
					System.out.println("Sleeping");
					TimeUnit.SECONDS.sleep(1);
					// point2
					NeedCleanup n2 = new NeedCleanup(2);
					try {
						System.out.println("Calculating");
						for(int i = 1; i < 2500000; i++) {
							d = d + (Math.PI + Math.E) / d;
						}
						System.out.println("Finished time-consuming operation");
					} finally {
						n2.cleanup();
					}
				} finally {
					n1.cleanup();
				}
			}
			System.out.println("Exiting via while() test");
		} catch (InterruptedException e) {
			System.out.println("Exiting via InterruptedException");
		}
	}
	
}
